package com.duowan.cms.intf.outside;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.duowan.cms.common.domain.Page;
import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.util.UrlUtil;
import com.duowan.cms.common.webapp.content.SpringApplicationContextHolder;
import com.duowan.cms.core.rmi.client.article.Article4TagListRemoteService;
import com.duowan.cms.core.rmi.client.article.ArticleRemoteService;
import com.duowan.cms.core.rmi.client.channel.ChannelRemoteService;
import com.duowan.cms.dto.article.Article4TagListInfo;
import com.duowan.cms.dto.article.Article4TagListSearchCriteria;
import com.duowan.cms.dto.article.Article4TagListSearchCriteria.Article4TagListOrderBy;
import com.duowan.cms.dto.article.ArticleInfo;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.intf.tougao.TougaoArticleServlet;
import com.duowan.cms.intf.util.IPFilter;

public class ArticleInfoServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(TougaoArticleServlet.class);
    
    private static final String ARTICLELIST_ALLOWEDIP = "ip_getArticleInfo";
    
    /**
     * 
     * 处理GET请求
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * 处理POST请求
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        
        // 添加IP限制
        String ip = IPFilter.getRealIp(request);
        if (!IPFilter.isLegalIp(ip, ARTICLELIST_ALLOWEDIP)) {
            logger.warn("the remote ip:" + ip + " is not allowed to use this interface.");
            response.getWriter().write("{\"describe\" : \" you are not allowed to use this interface.\"}");
            return;
        }
        
        String channelId = request.getParameter("channelId");
        ChannelRemoteService channelRemoteService = SpringApplicationContextHolder.getBean("channelRemoteService", ChannelRemoteService.class);
        ChannelInfo channelInfo = channelRemoteService.getById(channelId);
        if(null == channelInfo){
            logger.warn("cms can't find the channel by channelId:" + channelId);
            response.getWriter().write("{\"describe\" : \"cms can't find the channel by channelId:" + channelId + "\"}");
            return;
        }
        
        String m = request.getParameter("m");
        if("list".equals(m)){
            list(request, response);
        }else if("getById".equals(m)){
            getById(request, response);
        }else {
            response.getWriter().write("{\"describe\" : \"error:the parameter 'm'\"}");
        }
    }
    
    
    private String list2JsonString(Page<Article4TagListInfo> page){
        
        if(null == page || page.isEmpty()){
            return "{}";
        }
        
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"totalCount\":").append(page.getTotalCount()).append(",");
        sb.append("\"totalPageCount\":").append(page.getTotalPageCount()).append(",");
        sb.append("\"list\":[");
        boolean flag = false;
        for(Article4TagListInfo a : page.getData()){
            if(flag){
                sb.append(",{");
            }else{
                sb.append("{");
                flag = true;
            }
            sb.append("\"channelId\":\"").append(a.getChannelId()).append("\",");
            sb.append("\"id\":\"").append(a.getId()).append("\",");
            //sb.append("\"channelName\":\"").append(a.getChannelInfo().getName()).append("\",");
            //sb.append("\"tag\":\"").append(a.getTag()).append("\",");
            sb.append("\"title\":\"").append(null2EmptyEncode(a.getTitle())).append("\",");
            sb.append("\"titleColor\":\"").append(null2Empty(a.getTitleColor())).append("\",");
            sb.append("\"subtitle\":\"").append(null2EmptyEncode(a.getSubtitle())).append("\",");
            sb.append("\"digest\":\"").append(null2EmptyEncode(a.getDigest())).append("\",");
            sb.append("\"emptyLink\":\"").append(null2Empty(a.getEmptyLink())).append("\",");
            sb.append("\"pictureUrl\":\"").append(null2Empty(a.getPictureUrl())).append("\",");
            sb.append("\"source\":\"").append(null2EmptyEncode(a.getSource())).append("\",");
            sb.append("\"author\":\"").append(null2EmptyEncode(a.getAuthor())).append("\",");
            sb.append("\"userId\":\"").append(null2EmptyEncode(a.getUserId())).append("\",");
            //sb.append("\"dayNum\":\"").append(a.getDayNum()).append("\",");
            sb.append("\"url\":\"").append(a.getUrl()).append("\",");
            sb.append("\"publishTime\":\"").append(a.getPublishTimeStr()).append("\",");
            //sb.append("\"lastUpdateTime\":\"").append(a.getLastUpdateTimeStr()).append("\",");
            sb.append("\"diy1\":\"").append(null2EmptyEncode(a.getDiy1())).append("\",");
            sb.append("\"diy2\":\"").append(null2EmptyEncode(a.getDiy2())).append("\",");
            sb.append("\"diy3\":\"").append(null2EmptyEncode(a.getDiy3())).append("\",");
            sb.append("\"diy4\":\"").append(null2EmptyEncode(a.getDiy4())).append("\",");
            sb.append("\"diy5\":\"").append(null2EmptyEncode(a.getDiy5())).append("\"");
            sb.append("}");
        }
        sb.append("]");
        sb.append("}");
        
        return sb.toString();
    }
    
    
    
    private String null2EmptyEncode(String str){
        if(StringUtil.isEmpty(str)){
            return "";
        }
        return UrlUtil.encode(str);
    }
    
    private String null2Empty(String str){
        if(StringUtil.isEmpty(str)){
            return "";
        }
        return str;
    }
    
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String channelId = request.getParameter("channelId");
        String tags = request.getParameter("tags");
        if(StringUtil.isEmpty(tags)){
            logger.warn("tags is empty");
            response.getWriter().write("{\"describe\" : \"error:tags is empty\"}");
            return;
        }else{
            logger.info("the request parameter 'tags' : " + tags);
        }
        
        //默认第一页
        String pageNo = request.getParameter("pageNo");
        //默认每页二十五条记录
        String pageSize = request.getParameter("pageSize");
        
        String publishTimeStart = request.getParameter("timeStart");
        
        String publishTimeEnd = request.getParameter("timeEnd");
        
        Article4TagListSearchCriteria searchCriteria = new Article4TagListSearchCriteria();
        searchCriteria.setChannelId(channelId);
        searchCriteria.addTags(tags);
        if(StringUtil.isNumber(pageNo)){
            searchCriteria.setPageNo(Integer.parseInt(pageNo));
        }
        if(StringUtil.isNumber(pageSize)){
            searchCriteria.setPageSize(Integer.parseInt(pageSize));
        }
        
        try{
            if(!StringUtil.isEmpty(publishTimeStart)){
                searchCriteria.setPublishTimeStart(DateUtil.convertStr2Date(publishTimeStart));
            }
            if(!StringUtil.isEmpty(publishTimeEnd)){
                searchCriteria.setPublishTimeEnd(DateUtil.convertStr2Date(publishTimeEnd));
            }
        }catch(Exception e){
            logger.warn("", e);
        }
        
        searchCriteria.addOrderBy(Article4TagListOrderBy.DAY_NUM_DESC)
                        .addOrderBy(Article4TagListOrderBy.POWER_DESC)
                        .addOrderBy(Article4TagListOrderBy.POST_TIME_DESC);
        
        Article4TagListRemoteService article4TagListRemoteService = SpringApplicationContextHolder.getBean("article4TagListRemoteService", Article4TagListRemoteService.class);
        
        Page<Article4TagListInfo> page = article4TagListRemoteService.pageSearch(searchCriteria);
        
        response.getWriter().write(list2JsonString(page));
    }
    
    private void getById(HttpServletRequest request, HttpServletResponse response) throws IOException{
        
        String articleId = request.getParameter("articleId");
        String channelId = request.getParameter("channelId");
        
        if(StringUtil.isNumber(articleId)){
            ArticleRemoteService articleRemoteService = SpringApplicationContextHolder.getBean("articleRemoteService", ArticleRemoteService.class);
            ArticleInfo a = articleRemoteService.getByChannelIdAndArticleId(channelId, Long.parseLong(articleId));
            response.getWriter().write(article2JsonString(a));
        }else{
            response.getWriter().write("{\"describe\" : \"error:articleId\"}");
        }
        
    }
    
    private String article2JsonString(ArticleInfo a){
        
        if(null == a){
            return "{}";
        }
        
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"id\":\"").append(a.getId()).append("\",");
        sb.append("\"channelId\":\"").append(a.getChannelInfo().getId()).append("\",");
        sb.append("\"title\":\"").append(null2EmptyEncode(a.getTitle())).append("\",");
        sb.append("\"titleColor\":\"").append(null2Empty(a.getTitleColor())).append("\",");
        sb.append("\"subtitle\":\"").append(null2EmptyEncode(a.getSubtitle())).append("\",");
        sb.append("\"digest\":\"").append(null2EmptyEncode(a.getDigest())).append("\",");
        sb.append("\"pictureUrl\":\"").append(a.getPictureUrl()).append("\",");
        sb.append("\"source\":\"").append(null2EmptyEncode(a.getSource())).append("\",");
        sb.append("\"author\":\"").append(null2EmptyEncode(a.getAuthor())).append("\",");
        sb.append("\"userId\":\"").append(null2EmptyEncode(a.getUserId())).append("\",");
        sb.append("\"publishTime\":\"").append(a.getPublishTimeStr()).append("\",");
        sb.append("\"content\":\"").append(null2EmptyEncode(a.getContent())).append("\",");
        sb.append("\"url\":\"").append(a.getUrlOnLine()).append("\",");
        sb.append("\"diy1\":\"").append(null2EmptyEncode(a.getDiy1())).append("\",");
        sb.append("\"diy2\":\"").append(null2EmptyEncode(a.getDiy2())).append("\",");
        sb.append("\"diy3\":\"").append(null2EmptyEncode(a.getDiy3())).append("\",");
        sb.append("\"diy4\":\"").append(null2EmptyEncode(a.getDiy4())).append("\",");
        sb.append("\"diy5\":\"").append(null2EmptyEncode(a.getDiy5())).append("\"");
        sb.append("}");
        
        return sb.toString();
    }
    
}
